﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using static SuperX.Helper.OS.OSCommand;

namespace SuperX.Helper.OS.LinuxCmds
{
    /// <summary>
    /// 管理chrony工具，用于时间同步
    /// 配置文件：/etc/chrony.conf
    /// chrony是CentOS7.x上自带的时间同步软件
    /// chrony与ntp都是时间同步软件
    /// </summary>
    internal class ChronyManager
    {
        const string ChronyDService = "chronyd.service";
        const string ConfFullName = "/etc/chrony.conf";

        public NTPContext ReadNTPContext()
        {
            if (!File.Exists(ConfFullName) || !IsChronyRunning())
            {
                return new NTPContext();
            }
            var lines = File.ReadAllLines(ConfFullName);
            var servers = new List<string>();
            var isNtpServer = false;
            foreach (var line in lines)
            {
                if (line.StartsWith("server "))
                {
                    var splits = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    servers.Add(splits[1]);
                }
                if (line.StartsWith("local "))
                {
                    isNtpServer = true;
                }
            }
            return new NTPContext()
            {
                NTPServerIP = servers.FirstOrDefault(),
                EnableNTPClient = servers.Count > 0,
                EnableNTPServer = isNtpServer
            };
        }

        public void SetNTPContext(NTPContext ntpContext)
        {
            if (ntpContext == null || ntpContext.EnableNTPClient && string.IsNullOrWhiteSpace(ntpContext.NTPServerIP))
            {
                return;
            }
            var lines = File.ReadAllLines(ConfFullName).ToList();
            bool isChanged = false;
            if (ntpContext.EnableNTPClient)
            {
                var startContent = "server " + ntpContext.NTPServerIP;

                if (lines.All(line => !line.StartsWith(startContent)))
                {
                    lines.Insert(0, startContent + " iburst");
                    isChanged = true;
                }
            }
            if (ntpContext.EnableNTPServer)
            {
                if (lines.All(line => !line.StartsWith("#local ")))
                {
                    lines.Add("local stratum 10");
                    isChanged = true;
                }
                if (lines.All(line => !line.StartsWith("allow ")))
                {
                    lines.Add("allow");
                    isChanged = true;
                }
            }
            if (isChanged)
            {
                File.WriteAllLines(ConfFullName, lines);
            }
            LinuxCommand.Bash("systemctl restart " + ChronyDService);
        }

        public bool IsChronyRunning()
        {
            var result = LinuxCommand.Bash("systemctl status " + ChronyDService);
            if (result?.Contains("Active: active (running)") == true)
            {
                return true;
            }
            return false;
        }
    }
}
